#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void QuickSort(int* a, int left, int end);
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n) {
    int* num = malloc((n + m) * sizeof(int));
    for (int i = 0, j = 0; i < m + n; i++) {
        if (i < m)
            num[i] = nums1[i];
        else {
            num[i] = nums2[j];
            j++;
        }
    }
    QuickSort(num, 0, n + m - 1);
    for (int i = 0; i < n + m; i++) {
        if (i >= nums1Size) {
            int* new = realloc(nums1, (n + m) * sizeof(int));
            nums1 = new;
        }
        else {
            nums1[i] = num[i];
        }
    }
}
int minimumDifference(int* nums, int numsSize, int k) {
    if (k <= 1)
        return 0;
    QuickSort(nums, 0, numsSize - 1);
    int x = nums[k - 1] - nums[0];
    for (int i = 0; i < numsSize && i + k < numsSize; i++) {
        int y = nums[i + k-1] - nums[i];
        x = x < y ? x : y;
    }
    return x;
}
void QuickSort(int* a, int left, int end) {
    if (left >= end) {
        return;
    }
    int x = left, y = end;
    int pivot = x;
    int key = a[pivot];
    while (x < y) {
        while (x < y && a[y] >= key) {
            y--;
        }
        a[pivot] = a[y];
        pivot = y;
        while (x < y && a[x] <= key) {
            x++;
        }
        a[pivot] = a[x];
        pivot = x;
    }
    pivot = x;
    a[pivot] = key;
    QuickSort(a, 0, pivot - 1);
    QuickSort(a, pivot + 1, end);
}
int main() {
    /*int a[] = { 1,2,3,0,0,0 };
    int b[] = { 2,5,6 };
    int k1 = sizeof(a) / sizeof(int);
    int k2 = sizeof(b) / sizeof(int);
    merge(a, k1, 3, b, k2, 3);
    k1 = sizeof(a) / sizeof(int);
    for (int i = 0; i < k1; i++) {
        printf("%d ", a[i]);
    }*/
    int a[] = { 9,4,1,7 };
    int b = minimumDifference(a, 4, 2);
    printf("%d", b);
}